package eyou.net.treeview;;

import android.util.Log;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import okhttp3.Authenticator;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;

/**
 * Created by eYou on 2017/7/17.
 */

public class NetUtil {
    public static final String BASE_URL = "http://101.236.38.80";//外网联系人  zhouyy
    public static   String FETCH_EIS_URL = BASE_URL+"/plugin/user/group/";
    public static NetUtil   instance;
    public static synchronized  NetUtil getInstance() {
        if (instance == null) {
            instance = new NetUtil();
        }
        return instance;
    }

    public JSONObject fetch35EIS( Response   response ) throws Exception {

        InputStream inputStream = response.body().byteStream();//zhouyy
        JSONObject json = null;
        try {
            StringBuilder  stringBuilder=new StringBuilder();
            InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            reader.close();
            json = new JSONObject(stringBuilder.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }


    /**
     * zhouyy  Get  请求   basic认证
     * @return
     */
    public  Response Authenticate(final String account,String param)  {
        OkHttpClient client = new OkHttpClient.Builder()
                .authenticator(new Authenticator() {
                    @Override public Request authenticate(Route route, Response response) throws IOException {
                        System.out.println("Authenticating for response: " + response);
                        System.out.println("Challenges: " + response.challenges());
                        String credential = Credentials.basic("admin@test.eyou.net", "eyouadmin");
                        return response.request().newBuilder()
                                .header("Authorization", credential)
                                .build();
                    }
                })
                .build();
        Request request = new Request.Builder()
                .url(FETCH_EIS_URL+param)
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
            Log.i("TAG---> e",e.toString());
        }
        return response;
    }


}
